package com.shaw.workrecord.utils;

import cn.hutool.core.lang.UUID;
import com.shaw.workrecord.enums.GameType;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;


/**
 * @author jiangjunhui
 * @description
 * @date 2022/9/15 21:58
 */
public class MQTTUtils {

    public static final String BROKER = "ws://124.221.2.154:8083/mqtt";
    public static final Integer QOS = 2;

    private static MqttAsyncClient client;

    public static void createClient() {
        String broker = BROKER;
        String clientId = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttConnectionOptions connOpts = new MqttConnectionOptions();
            connOpts.setCleanStart(false);
            client = new MqttAsyncClient(broker, clientId, persistence);
            System.out.println("Connecting to broker: " + broker);
            IMqttToken token = client.connect(connOpts);
            token.waitForCompletion();
            System.out.println("Connected");
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }

    public static void pushMessage(GameType gameType, Long roomId, String content) {
        System.out.println("Publishing message: " + content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(QOS);
        IMqttToken token = null;
        try {
            token = client.publish("game/" + gameType.getType() + "/" + roomId, message);
            token.waitForCompletion();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static void close() {
        if (client == null) {
            return;
        }
        try {
            client.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        System.out.println("Disconnected");
        System.out.println("Close client.");
    }

}
